package com.cztv.vote.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import com.cztv.vote.bean.VoteProjectBean;

public class VoteDao extends SimpleJdbcDaoSupport{

	public void insert() {
		String sql = "select r_id from votes where";
		// this.getJdbcTemplate().execute();
	}

	public void update() {

	}
	
	public int queryCountByIp(String ip){
		String sql = "select count(*) from votelogs where v_ip=?";
		int count=this.getJdbcTemplate().queryForInt(sql, new Object[]{ip});
		return count;
	}

	public Object queryById(int rid) {
		String sql = "select * from project where p_id=(select p_id from register where r_id=?)";
		
		Object obj=this.getJdbcTemplate().queryForObject(sql, new Object[]{rid}, new RowMapper(){

			public Object mapRow(ResultSet rs, int index) throws SQLException {
				VoteProjectBean bean=new VoteProjectBean();
				bean.setCode(rs.getInt("is_code")==1?true:false);
				bean.setIp(rs.getInt("is_ip")==1?true:false);
				bean.setIspOpen(rs.getInt("p_open")==1?true:false);
				bean.setVoteNum(rs.getInt("is_webvote")==1?true:false);
				
				int unit=rs.getInt("p_unit");
				int ipTimelimit=rs.getInt("is_iptime");
				
				bean.setIpTimeLimit(unit*ipTimelimit);
				bean.setVoteNumLimit(rs.getInt("is_votenum"));
				
				bean.setRegtime(rs.getLong("p_regtime"));
				bean.setEndtime(rs.getLong("p_offtime"));
				
				return bean;
			}
			
		});
		
		return obj;
	}

	public int testQuery(int rid) {
		String sql = "select votes from votes where r_id=?";

		int result = this.getJdbcTemplate().queryForInt(sql,
				new Object[] { rid });

		return result;
	}
	
	public static void main(String[] args){
		ApplicationContext ctx = new ClassPathXmlApplicationContext("config/applicationContext.xml");  
		VoteDao dao=(VoteDao) ctx.getBean("voteDao");
		System.out.println(dao.testQuery(3));
	}
}
